/**
 * 
 */
package net.frankish.logging;

import java.io.File;
import java.io.IOException;
import java.util.logging.ConsoleHandler;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

/**
 * @author Frankish
 *
 */
public class FrankishLogging {

	private static FrankishLogging instance = null;
	private Level baseLevel;
	private int memoryConsoleLimit; 
	private FrankishLogging(){
		baseLevel = Level.parse(System.getProperty("net.frankish.logging.level", "INFO"));
		memoryConsoleLimit = Integer.parseInt(System.getProperty("net.frankish.logging.memoryConsoleLimit", "300"));
		LogManager.getLogManager().reset();
		Logger.getLogger("").setLevel(Level.WARNING);
		Logger.getLogger("net.frankish").setLevel(baseLevel);
		if(Boolean.getBoolean("net.frankish.logging.defaultfilelogging")){
			setFileHandler("net.frankish","./log/["+new java.sql.Date(System.currentTimeMillis())+"]FrankishNet.log");
		}
		if(Boolean.getBoolean("net.frankish.logging.defaultconsolelogging")){
			ConsoleHandler hand = new ConsoleHandler();
			hand.setLevel(baseLevel);
			hand.setFormatter(new SimpleFormatter());
			Logger.getLogger("net.frankish").addHandler(hand);
		}
		Logger.getLogger("net.frankish").addHandler(new MemoryLogHandler(memoryConsoleLimit));
	}
	
	public void setFileHandler(String packg, String logFile){
		try {
			File file = new File(logFile.substring(0,logFile.lastIndexOf("/")));
			file.mkdirs();
			FileHandler hand = new FileHandler(logFile,true);
			hand.setLevel(baseLevel);
			hand.setFormatter(new SimpleFormatter());
			Logger.getLogger(packg).addHandler(hand);
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static FrankishLogging getInstance(){
		if(instance == null)
			instance = new FrankishLogging();
		return instance;
	}
}
